package com.genymobile.scrcpy.five.config.parser;

import com.genymobile.scrcpy.five.config.IEventMap;

import java.util.regex.Pattern;

public class InputDumpParser13 implements IDumpInputParser {

    private final Pattern eventNodePattern;
    private final Pattern displayIdPattern;
    private final AospEventMap eventMap;
    public InputDumpParser13() {
        eventNodePattern = Pattern.compile("event[0-9]+");
        displayIdPattern = Pattern.compile("displayId=[0-9]+");
        eventMap = new AospEventMap();
    }

    @Override
    public String getDumpsysInputCmd() {
        return "dumpsys input | egrep 'Device [0-9]+.+event[0-9]+$|Viewport.+displayId=' | egrep 'event[0-9]+|displayId=[0-9]+' -o";
    }

    @Override
    public IEventMap getResult() {
        return eventMap;
    }

    private String lastEventNode = null;
    @Override
    public boolean handleLine(boolean firstLine, String line) {
        if (eventNodePattern.matcher(line).find()) {
            lastEventNode = "/dev/input/" + line;
        } else if (displayIdPattern.matcher(line).find()) {
            int displayId = -1;
            try {
                displayId = Integer.parseInt(line.replace("displayId=", ""));
            } catch (Exception ignored) {}
            if (displayId >= 0 && lastEventNode != null) {
                eventMap.add(lastEventNode, displayId);
                lastEventNode = null;
            }
        }
        return false;
    }
}
